﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

//移动的平台，不一定是Tilemap
public class Platform_Movable : MonoBehaviour
{
    private EventSystem eventSystem;

    public float speed = 6f;
    [SerializeField]
    private Vector2 _Direciton;
    public Vector2 Direction
    {
        get => _Direciton;
        protected set
        {
            _Direciton = value;
            deltaPosition = speed * Time.fixedDeltaTime * value;
        }
    }
    [SerializeField]
    //是否在每次重置时立刻开始移动
    private bool b_startOnAwake;
    [HideInInspector]
    public bool b_started;
    
    protected Vector3 defaultPosition;
    protected Vector2 defaultDirection;
    protected Vector3 deltaPosition;

    private void Awake()
    {
        eventSystem = Service.Get<EventSystem>();
        Direction = _Direciton.normalized;
        defaultDirection = Direction;
        defaultPosition = transform.position;

        if (b_startOnAwake)
            b_started = true;
    }
    protected virtual void OnEnable()
    {
        eventSystem.PlayerDie += MyReset;
    }
    protected virtual void OnDisable()
    {
        eventSystem.PlayerDie -= MyReset;
    }

    public void MyReset()
    {
        b_started = false;
        if (b_startOnAwake)
            b_started = true;
        transform.position = defaultPosition;
        Direction = defaultDirection;
    }
    //可延时启动
    public void DelayStart(float t = 0)
    {
        StartCoroutine(DelayStart_(t));
    }
    private IEnumerator DelayStart_(float t)
    {
        yield return new WaitForSeconds(t);
        b_started = true;
    }

    public void DelayStop(float t = 0)
    {
        StartCoroutine(DelayStop_(t));
    }
    public IEnumerator DelayStop_(float t)
    {
        yield return new WaitForSeconds(t);
        b_started = false;
    }

    protected void FixedUpdate()
    {
        if (b_started)
            Move();
        if (transform.position.magnitude > 1000f)
            DelayStop();
    }
    
    protected virtual void Move()
    {
        transform.position += deltaPosition; 
    }

    protected void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.gameObject.GetComponent<Character>() != null)
            OnTouchPlayer();
        else
            OnTouchObstacle();
    }

    protected virtual void OnTouchPlayer() { }
    protected virtual void OnTouchObstacle() { }
}
